package com.appology.chuck;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.*;

import com.appology.jokes.Joke;
import com.google.api.client.extensions.auth.helpers.Credential;
import com.google.api.services.buzz.Buzz;
import com.google.api.services.buzz.Buzz.People;
import com.google.api.services.buzz.Buzz.People.Get;
import com.google.api.services.buzz.model.Activity;
import com.google.api.services.buzz.model.ActivityFeed;
import com.google.api.services.buzz.model.Person;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.users.User;


@SuppressWarnings("serial")
public class BetterthanchuckServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		
        String thisURL = request.getRequestURI();
	    if (request.getParameter("addJokes") != null && request.getParameter("addJokes").equalsIgnoreCase("true")){
    		Joke.getInstance().AddItemsToDB();
        } else {
	        if (request.getUserPrincipal() != null) { 
	        	ChuckUser chuckUser = ChuckUserBuilder.getChuckUserByGoogleId(userService.getCurrentUser().getUserId());
	        	
	        	if(chuckUser == null){
	            response.getWriter().println(Joke.getInstance().getRandom(userService.getCurrentUser().getNickname()));
	        	} else{
	        		response.getWriter().println(Joke.getInstance().getRandom(chuckUser.getDisplayName()));
	        	}
	            
	            
	        } else {
	        	User user = userService.getCurrentUser();
	        	String joke = Joke.getInstance().getRandom(null);
	        	response.getWriter().println(joke);
	
	        }
        }
	}
	 
}
